import React, { useEffect, useState } from 'react';
import { Form, Modal } from 'antd';

import './styles/transfer.less';

import TransferType from './TransferType';

import { useMenuContext } from '../Context/MenuContext';
import AgentService from '@/modules/Agent';
import TransferForm from './TransferForm';
import InviteForm from './InviteForm';
import TransferHeader from './TransferHeader';
import { SelectAgentOptions } from '@/modules/interface';

interface TransferProps {
	visible?: boolean;
	searchAgentBindBizScenario?: any;
	fields?: any;
	title?: string;
	transferError?: boolean;
	bizScenarioTransfer?: (form: any) => void;
	onClose?: () => void;
	onChangeBizScenario?: (e: any) => void;
	inviteAgent: (data: { agentName?: string; groups: { id: number; name: string }[] | null; mode: 'agent' | 'groupSkill' }) => void;
	agentTransfer: (data: { agentName?: string; groups: { id: number; name: string }[] | null; mode: 'agent' | 'groupSkill' }) => void;
	inviteOtherStatus?: string;
	inviteAgentError?: string;
	groupSkillError?: string;
	bizScenarioTransferToScenErrorText?: string;

	bizScenarioTransferToAgentErrorText?: string;
	bizScenarioTransferGroupSkill?: string;
	transferAgentIdErrorText?: string;
}

const Transfer = (props: TransferProps) => {
	const {
		visible = false,
		fields,
		title,
		bizScenarioTransfer,
		onClose,
		inviteAgent,
		agentTransfer,
		searchAgentBindBizScenario,
		groupSkillError,
		transferError,
		onChangeBizScenario,
		inviteOtherStatus,
		inviteAgentError,
		bizScenarioTransferGroupSkill,
		bizScenarioTransferToScenErrorText,
		bizScenarioTransferToAgentErrorText,
		transferAgentIdErrorText
	} = props;

	const [tabsType, setTabsType] = useState<'sceneTransfer' | 'agentTransfer' | 'inviteAgent' | 'inviteClient'>('sceneTransfer');

	const { menuState, setMenuState } = useMenuContext();
	const [selectedGroupSkill, setSelectedGroupSkill] = useState<{ id: number; name: string }[]>([]);
	const [headerOptions, setHeaderOptions] = useState<{ label: string; value: string; disable?: boolean }[]>(AgentService.getTransferHeaderOptions());
	const [defaultChecked, setDefaultChecked] = useState<string>('default');
	const [defaultScene, setDefaultScene] = useState<string>(AgentService.bizScenarioId);
	const [skillGroups, setSkillGroups] = useState<{ id: number; name: string }[]>([]);
	const [selectAgentOptions, setSelectAgentOptions] = useState<SelectAgentOptions[]>([]);
	const [bizScenarioID, setBizScenarioID] = useState<string | undefined>(undefined);
	const [requestDatasource, setRequestDatasource] = useState<boolean>(false);

	useEffect(() => {
		if (tabsType === 'agentTransfer' || tabsType === 'inviteAgent') {
			AgentService.fetchGroupWithBizscenariosID(Number(AgentService.bizScenarioId), true).then(resp => {
				setSkillGroups(AgentService.getGroupSkill());
			});
		} else {
			setSkillGroups([]);
		}
		setSelectedGroupSkill([]);
		setSelectAgentOptions([]);
		setDefaultChecked('default');
	}, [visible]);

	useEffect(() => {
		setDefaultScene(AgentService.bizScenarioId);
		setSelectAgentOptions([]);
		setSelectedGroupSkill([]);
		if (inviteOtherStatus === 'transfer') {
			setTabsType('sceneTransfer');
		} else {
			setTabsType('inviteAgent');
		}
		getModalView();
	}, [inviteOtherStatus]);

	useEffect(() => {
		setDefaultChecked('default');
		if (tabsType === 'agentTransfer' || tabsType === 'inviteAgent') {
			AgentService.fetchGroupWithBizscenariosID(Number(AgentService.bizScenarioId), true).then(resp => {
				setSkillGroups(AgentService.getGroupSkill());
			});
		}

		if (tabsType === 'sceneTransfer') {
			setSkillGroups([]);
		}
		setSelectAgentOptions([]);
		setBizScenarioID(undefined);
	}, [tabsType]);

	const changeGroupSkill = (value: any, options: any) => {
		const list = options.map((item: any) => ({ id: item.value, name: item.children }));
		setSelectedGroupSkill(list);
		setMenuState({
			...menuState,
			bizScenarioTransferGroupSkill: ''
		});
	};

	const onReset = () => {
		setBizScenarioID(undefined);
		onClose && onClose();
	};

	const submit = (value: any) => {
		const { no, groups, transferScene } = value;
		if (tabsType === 'sceneTransfer') {
			bizScenarioTransfer && bizScenarioTransfer({ mode: defaultChecked, agentName: no, groups, transferScene: Number(transferScene) });
		} else {
			agentTransfer({ mode: defaultChecked as any, agentName: no, groups });
		}
		setSelectedGroupSkill([]);
		setBizScenarioID(undefined);
	};

	const changeScenario = async (value: number) => {
		setBizScenarioID(value.toString());
		await AgentService.fetchGroupWithBizscenariosID(value, true);
		await AgentService.fetchBizscenariosAgents(value.toString());
		setSelectAgentOptions([]);
		setSelectedGroupSkill([]);
		setSkillGroups(AgentService.getGroupSkill());
		onChangeBizScenario && onChangeBizScenario(value);
	};

	const headerChangeHandler = (value: string) => {
		setMenuState({
			...menuState,
			inviteAgentError: '',
			groupSkillError: '',
			bizScenarioTransferToScenErrorText: '',
			bizScenarioTransferToAgentErrorText: '',
			transferAgentIdErrorText: '',
			bizScenarioTransferGroupSkill: ''
		});
		setSelectedGroupSkill([]);
		setDefaultChecked(value);
	};

	const getGroupScene = () => {
		if (!AgentService.bizScenarioId) return [];
		return AgentService.getAllGroupScene().filter(item => item.id !== Number(AgentService.bizScenarioId));
	};

	const onDropdown = async () => {
		setSelectAgentOptions([]);
		setRequestDatasource(true);
		if (tabsType === 'sceneTransfer') {
			if (!bizScenarioID) {
				setSelectAgentOptions([]);
			} else {
				await AgentService.fetchBizscenariosAgents(bizScenarioID);
				const list = AgentService.getBizscenariosAgents().map(item => ({ label: item.userName, value: item.userName, id: item.id, status: item.status, fullName: item.fullName || '' }));
				if (AgentService.bizScenarioId !== bizScenarioID) {
					setSelectAgentOptions(list);
				} else {
					setSelectAgentOptions(list.filter(k => k.label !== AgentService.user?.userName));
				}
				setRequestDatasource(false);
			}
		} else {
			await AgentService.fetchBizscenariosAgents(AgentService.bizScenarioId);
			const list = AgentService.getBizscenariosAgents().map(item => ({ label: item.userName, value: item.userName, id: item.id, status: item.status, fullName: item.fullName || '' }));
			setSelectAgentOptions(list.filter(k => k.label !== AgentService.user?.userName));
			setRequestDatasource(false);
		}
		setMenuState({
			...menuState,
			inviteAgentError: '',
			groupSkillError: '',
			bizScenarioTransferToScenErrorText: '',
			bizScenarioTransferToAgentErrorText: '',
			transferAgentIdErrorText: '',
			bizScenarioTransferGroupSkill: ''
		});

		console.log('onDropdown:', tabsType, AgentService.getBizscenariosAgents(), bizScenarioID);
	};
	const onScroll = () => {};

	const getModalView = () => {
		if (inviteOtherStatus === 'transfer')
			return (
				<>
					<TransferForm
						onDropdown={onDropdown}
						onScroll={onScroll}
						skillGroups={skillGroups}
						sceneList={getGroupScene()}
						selectedGroupSkill={selectedGroupSkill}
						defaultChecked={defaultChecked}
						headerOptions={headerOptions}
						bizScenarioTransferToScenErrorText={bizScenarioTransferToScenErrorText}
						bizScenarioTransferToAgentErrorText={bizScenarioTransferToAgentErrorText}
						bizScenarioTransferGroupSkill={bizScenarioTransferGroupSkill}
						transferAgentIdErrorText={transferAgentIdErrorText}
						selectAgentOptions={selectAgentOptions}
						headerChangeHandler={headerChangeHandler}
						type={tabsType}
						defaultScene={defaultScene}
						submit={submit}
						onReset={onReset}
						changeGroupSkill={changeGroupSkill}
						changeScenario={changeScenario}
						requestDatasource={requestDatasource}
					/>
				</>
			);
		if (inviteOtherStatus === 'invite')
			return (
				<InviteForm
					onCancel={onReset}
					changeGroupSkill={() =>
						setMenuState({
							...menuState,
							groupSkillError: ''
						})
					}
					selectAgentOptions={selectAgentOptions}
					groupSkillError={groupSkillError}
					inviteAgentError={inviteAgentError}
					inviteAgent={inviteAgent}
					onDropdown={onDropdown}
					onScroll={onScroll}
					type={tabsType}
					requestDatasource={requestDatasource}
				></InviteForm>
			);
	};

	const getModalHeader = () => {
		return (
			<TransferType
				tabsType={tabsType}
				showTransferScene={AgentService.configure.isTransferScene}
				inviteOtherStatus={inviteOtherStatus}
				onClick={role => {
					setTabsType(role);
					setMenuState({
						...menuState,
						inviteAgentError: '',
						groupSkillError: '',
						bizScenarioTransferToScenErrorText: '',
						bizScenarioTransferToAgentErrorText: '',
						transferAgentIdErrorText: '',
						bizScenarioTransferGroupSkill: ''
					});
				}}
			/>
		);
	};

	return (
		<Modal
			width={580}
			title={title}
			open={visible}
			destroyOnClose={true}
			footer={<></>}
			className="form-modal-container"
			onCancel={() => {
				onClose && onClose();
			}}
		>
			{getModalHeader()}
			{getModalView()}
		</Modal>
	);
};

export default Transfer;
